# -*- coding: utf-8 -*-

from xadmin.plugins.actions import BaseActionView
from django.template.response import TemplateResponse
from django.utils.encoding import force_unicode
from .models import *
from django.utils.translation import ugettext as _


class DemoAction(BaseActionView):

    # Action的唯一标示, 尽量用比较针对性的名字
    action_name = "Demo_Action"
    # 描述, 出现在 Action 菜单中, 可以使用 %(verbose_name_plural)s 代替 Model 的名字.
    description = u'设置免费 %(verbose_name_plural)s'

    # 该 Action 所需权限
    model_perm = 'change'

    # 实现方法
    def do_action(self, queryset):
        # queryset 是包含了已经选择的数据的 queryset
        for obj in queryset:
            obj.free = True
            obj.save()
        # 返回 HttpResponse
        return None


ACTION_CHECKBOX_NAME = '_selected_action'


class SubjectAction(BaseActionView):

    action_name = "Subject_Action"

    description = u'批量修改学科'

    model_perm = 'change'

    def do_action(self, queryset):
        """
        执行
        :param queryset:
        :return:
        """
        # 返回
        if self.request.POST.get('finish') and self.request.POST.get('action') == self.action_name:

            subjects = []
            for i in Subject.objects.all():
                if self.request.POST.get(str(i.id)) == u'on':
                    subjects.append(i)

            for i in queryset:
                i.subject = subjects
                i.save()

            return None

        # 确认页面
        return self.comfirm_view(queryset)

    def comfirm_view(self, queryset):
        """
        确认页面
        :param queryset:
        :return:
        """
        objects_name = force_unicode(self.opts.verbose_name)

        app_th = [u'姓名']
        app_td = [[app.name] for app in queryset]

        context = self.get_context()
        context.update({
            "title": _("Are you sure?"),
            "objects_name": objects_name,
            'queryset': queryset,
            "opts": self.opts,
            "app_label": self.app_label,
            'action_checkbox_name': ACTION_CHECKBOX_NAME,
            'subjects': Subject.objects.all(),
            'app_th': app_th,
            'app_td': app_td,
        })

        return TemplateResponse(self.request,
                                self.get_template_list('views/demo_confirm.html'),
                                context,
                                current_app=self.admin_site.name)

